///网络请求
import 'dart:convert';
import 'package:http/http.dart' as http;

//0正式 1测试
var URl = ["http://www.devio.org/io/flutter_app/json/" ,"http://www.devio.org/io/flutter_app/json/"];
//正式
var BASE_URL =URl[0];

class HttpUtils {
  static void get(String url, Function callback,
      {Map<String, String>? params, required Function errorCallback}) async {
    StringBuffer sb = StringBuffer("?");
    params?.forEach((key, value) {
      sb.write(key + "=" + "$value" + "&");
    });
    String paramStr = sb.toString();
    paramStr = paramStr.substring(0, paramStr.length - 1);
    print(BASE_URL + url + "接口入参：\n" + paramStr);
    url += paramStr;
    print(BASE_URL + url + "接口分割线：===================");
    try {
      http.Response res = await http.get(Uri.parse(BASE_URL + url));
      _success(url, res, callback, {});
    } catch (error) {
      errorCallback(error);
      print(url + "接口失败：\n" + error.toString());
    }
  }

  static void post(String url, Function callback,
      {Map<String, String>? params, required Function errorCallback}) async {
    try {
      http.Response res =
          await http.post(Uri.parse(BASE_URL + url), body: params);
      _success(url, res, callback, {params});
    } catch (e) {
      errorCallback(e);
    }
  }

  static void _success(String url, http.Response res, Function callback,
      Set<Map<String, String>?> set) {
    if (res.statusCode == 200) {
      Utf8Decoder utf8decoder = Utf8Decoder(); //修复中文乱码问题
      var result = json.decode(utf8decoder.convert(res.bodyBytes));
      print(BASE_URL + url + "接口数据返回：\n" + result.toString());
      callback(result);
    } else {
      throw Exception("加载Json失败");
    }
  }
}
